<template>
  <div>
    <div>
      <van-address-edit
        :address-info="detail"
        :area-list="areaList"
        show-delete
        show-set-default
        :area-columns-placeholder="['省', '市', '县']"
        @save="onSave"
      />
    </div>
  </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import {
  reqAddressAdd,
  reqAddressEdit,
  reqAddressList
} from "../../../http/api";
import { Toast } from "vant";
export default {
  data() {
    return {
      // 1.省市区的数据
      areaList,
      detail: {}
    };
  },
  mounted() {
    // 4.编辑进来了
    if (this.$route.query.id) {
      //此处是编辑进来的
      reqAddressList({
        uid: JSON.parse(localStorage.getItem("user")).uid,
        id: this.$route.query.id
      }).then(res => {
        let detail = res.data.list[0];

        this.detail = {
          name: detail.username,
          tel: detail.userphone,
          address: detail.location,
          areaCode: detail.regioncode,
          addressDetail: detail.useraddress,
          isDefault: detail.status == 1
        };
        this.tag = detail.label;
      });
    }
  },
  methods: {
    onSave(e) {
      // {"name":"zs","tel":"15718181818","country":"","province":"河北省","city":"唐山市","county":"路北区","areaCode":"130203","postalCode":"","addressDetail":"110","isDefault":true}
      if (this.$route.query.id) {
        //修改
        reqAddressEdit({
          username: e.name,
          userphone: e.tel,
          regioncode: e.areaCode,
          location: e.province + e.city + e.county,
          useraddress: e.addressDetail,
          status: e.isDefault ? 1 : 0,
          label: this.tag,
          id: this.$route.query.id
        }).then(res => {
          if (res.data.code == 200) {
            //弹成功
            Toast(res.data.msg);
            //跳转到list
            this.$router.replace("/site");
          }
        });
      } else {
        //添加
        //3.添加
        reqAddressAdd({
          uid: JSON.parse(localStorage.getItem("user")).uid,
          username: e.name,
          userphone: e.tel,
          regioncode: e.areaCode,
          location: e.province + e.city + e.county,
          useraddress: e.addressDetail,
          status: e.isDefault ? 1 : 0,
          label: this.tag
        }).then(res => {
          if (res.data.code == 200) {
            //弹成功
            Toast(res.data.msg);
            //跳转到list
            this.$router.replace("/site");
          }
        });
      }
    }
  }
};
</script>

<style>
</style>